<template>
  <div ref="chart" style="height: 100%;" />
</template>
<script>
import { Chart } from '@antv/g2';
export default {
/*
  data:     所要传输的数据
  x:        x轴变量名(有默认值)
  y:        y轴变量名(有默认值)
  color:    图表颜色
  text:     图表中的文字
  src:      字体图表地址
*/
  name: 'PieChart',
  props: {
    data: {
      type: Array,
      required: true
    },
    color: {
      type: Array,
      required: true
    },
    x: {
      type: String,
      default: 'x'
    },
    y: {
      type: String,
      default: 'y'
    },
    text: {
      type: String,
      required: true
    },
    src: {
      type: String,
      requried: false
    }
  },
  data() {
    return {
      chart: null
    };
  },
  watch: {
    data: function() {
      this.updataData();
    }
  },
  mounted() {
    this.init();
    this.drawChart();
  },
  methods: {
    init() {
      const ref = this.$refs.chart;
      this.chart = new Chart({
        container: ref,
        width: ref.clientWidth,
        height: ref.clientHeight
      });
    },
    drawChart() {
      const ratio = window.ratio || 1;
      const x = this.x;
      const y = this.y;
      this.chart.legend(false);
      this.chart.tooltip({
        showTitle: false,
        showMarkers: false,
        domStyles: {
          'g2-tooltip-title': {
            display: 'none',
            fontSize: '.875rem',
            color: '#8D8D8D'
          },
          'g2-tooltip-list-item': {
            fontSize: 0,
            overflow: 'hidden',
            margin: '.625rem 0 .3125rem 0'
          },
          'g2-tooltip-name': {
            fontSize: '.75rem',
            color: '#8D8D8D'
          },
          'g2-tooltip-value': {
            fontSize: '.75rem',
            color: 'rgba(0, 0, 0, 0.6)',
            fontWeight: '780'
          }
        }
      });
      this.chart.data(this.data);
      this.chart.coordinate('theta', {
        radius: 1,
        innerRadius: 0.82
      });
      // 标注
      this.chart.annotation().text({
        content: this.text,
        position: ['50%', '60%'],
        style: {
          fontSize: 12 * ratio,
          fontFamily: 'Helvetica-regular',
          fill: '#D9D9D9',
          textAlign: 'center'
        }
      });
      this.chart.annotation().image({
        src: this.src,
        start: ['43.125%', '34.56%'],
        end: ['56.88%', '50.74%']
      });
      this.chart
        .interval()
        .adjust('stack')
        .position(y)
        .color(x, this.color);
      this.chart.render();
    },
    updataData() {
      this.chart.changeData(this.data);
    }
  }
};
</script>
